package view.table.circle;

import java.awt.Component;
import java.util.ArrayList;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

import model.Circle;
import model.validation.ShapeValidationException;
import view.ControllerEventParser;
import view.IView;
import view.table.CellValueChangeEvent;
import view.table.CellValueChangeListener;
import appmodel.ControllerEvent;
import controller.Controller;

public class CircleView implements IView {

	private Controller controller;
	private Component swingView;
	private CircleTableModel circleTableModel;
	private JTable table;

	public CircleView(Controller controller) {
		super();
		this.controller = controller;
		circleTableModel = new CircleTableModel(new ArrayList<Circle>(controller.getCircles()));
		table = new JTable(circleTableModel);
		swingView = new JScrollPane(table);
		createSaveProvider(circleTableModel, swingView);
		controller.registerView(this);
	}

	private void createSaveProvider(final CircleTableModel circleModel, final Component component) {
		circleModel.setSaveProvider(new CellValueChangeListener() {

			@Override
			public void onChange(CellValueChangeEvent e) {
				Integer newValue = (Integer) e.getValueToChange();
				Circle circle = (Circle) e.getCurrentObject();
				int oldX = circle.getX();
				int oldY = circle.getY();
				int oldR = circle.getR();
				switch (e.getChangeAtColumn()) {
				case 0:
					circle.setX(newValue);
					break;
				case 1:
					circle.setY(newValue);
					break;
				case 2:
					circle.setR(newValue);
					break;
				default:

				}
				try {
					controller.editShape(circle);
				} catch (ShapeValidationException e2) {
					JOptionPane.showMessageDialog(component, "Invalid arguments");
					circle.setY(oldY);
					circle.setX(oldX);
					circle.setR(oldR);
				}
			}

		});
	}

	@Override
	public void onControllerEvent(ControllerEvent event) {
		ControllerEventParser parser = new ControllerEventParser(event) {
			public void addShape(Circle c) {
				circleTableModel.addCircle(c);
			};

			public void removeShape(Circle c) {
				circleTableModel.removeCircle(c);
			};
			public void refresh() {
				circleTableModel.setCircles(new ArrayList<Circle>(controller.getCircles()));
			}
		};
		parser.processEvent();
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				table.updateUI();
			}
		});
	}

	public Component getSwingView() {
		return swingView;
	}

}
